package com.codedancer.campus.client.aspect;

import com.codedancer.campus.common.anno.CommentNumber;
import com.codedancer.campus.common.utils.IpUtils;
import com.codedancer.campus.common.utils.RedisUtil;
import java.lang.reflect.Method;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 评论数量通知
 */
@Aspect
@Slf4j
@Configuration
public class CommentNumberAspect {

    @Autowired
    private RedisUtil redisUtil;
    // 注入评论记录redisTemplate
    @Resource(name = "commentRedisTemplate")
    private StringRedisTemplate commentRedisTemplate;


    /**
     * 获取当前的ServletRequest
     *
     * @return
     */
    protected HttpServletRequest servletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(
            RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.codedancer.campus.common.anno.CommentNumber)")
    public void commentNumberPointCut() {
    }

    /**
     * 切入处理，环绕通知
     *
     * @param joinPoint
     * @return
     */
    @Around("commentNumberPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        redisUtil.setRedisTemplate(commentRedisTemplate);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CommentNumber commentNumber = method.getAnnotation(CommentNumber.class);;
        Object[] args = joinPoint.getArgs();
        // uuid
        Object uuid = args[0];
        Object obj = null;
        try {
            // 获取请求的ip
            String ipAddr = IpUtils.getIpAddr(servletRequest());
            log.info("请求Ip：{}",ipAddr);
            // 设置存入的key
            String key = commentNumber.key() + uuid;
            log.info("key：{}",key);
            // 数量加1
            redisUtil.increment(key);
            obj = joinPoint.proceed();
        }catch (Exception e){
            e.fillInStackTrace();
        }
        return obj;
    }
}
